/*
 *Copyright 2021-2023 NERCIS
 *
 *Licensed under the Apache License, Version 2.0 (the "License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *Unless required by applicable law or agreed to in writing, software
 *distributed under the License is distributed on an "AS IS" BASIS,
 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *See the License for the specific language governing permissions and
 *limitations under the License.
 */

package cn.ac.nercis.pes.service.project.imported;

import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.project.ImportConflictDTO;
import cn.ac.nercis.pes.model.standard.planning.EvaluationRequireSDTO;
import cn.ac.nercis.pes.repository.dal.evaluation.EvaluationRequireRepository;
import cn.ac.nercis.pes.repository.model.evaluation.EvaluationRequireDO;
import cn.ac.nercis.pes.service.utils.CheckFieldUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 测评配合需求信息导入服务
 *
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public class EvaluationRequireImportService {
    private final EvaluationRequireRepository evaluationRequireRepository;

    @Autowired
    public EvaluationRequireImportService(EvaluationRequireRepository evaluationRequireRepository) {
        this.evaluationRequireRepository = evaluationRequireRepository;
    }

    public Result<List<ImportConflictDTO>> checkEvaluationRequire(@NonNull String systemId, List<EvaluationRequireSDTO> evaluationRequires) {
        List<EvaluationRequireDO> sourceData = this.evaluationRequireRepository.findAllBySystemId(systemId);
        if (CollectionUtils.isEmpty(sourceData)) {
            return Result.success();
        }
        List<ImportConflictDTO> conflictData = evaluationRequires.stream()
                .flatMap(ec -> this.checkEvaluationRequire(ec, sourceData).stream())
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        return Result.success(conflictData);
    }

    public Result<String> importEvaluationRequire(@NonNull String systemId, List<EvaluationRequireSDTO> evaluationRequires, Boolean cover) {
        List<EvaluationRequireDO> sourceData = this.evaluationRequireRepository.findAllBySystemId(systemId);
        Result<String> result = Result.success();
        for (EvaluationRequireSDTO item : evaluationRequires) {
            result = this.importEvaluationRequire(systemId, item, sourceData, cover);
            if (!result.isSuccess()) {
                break;
            }
        }
        return result;
    }

    private List<ImportConflictDTO> checkEvaluationRequire(@NonNull EvaluationRequireSDTO importData, List<EvaluationRequireDO> sourceData) {
        EvaluationRequireDO entity = sourceData.stream()
                .filter(st -> StringUtils.equals(st.getLayerTargetId(), importData.getLayerTargetId())
                        && StringUtils.equals(st.getProject(), importData.getProject()))
                .findFirst().orElse(null);
        if (Objects.isNull(entity)) {
            return Collections.emptyList();
        }
        return CheckFieldUtils.checkField(entity, importData);
    }

    private Result<String> importEvaluationRequire(String systemId, @NonNull EvaluationRequireSDTO importData, List<EvaluationRequireDO> sourceData, Boolean cover) {
        EvaluationRequireDO entity = sourceData.stream()
                .filter(st -> StringUtils.equals(st.getLayerTargetId(), importData.getLayerTargetId())
                        && StringUtils.equals(st.getProject(), importData.getProject()))
                .findFirst().orElse(null);
        if (Objects.isNull(entity)) {
            return createEvaluationRequire(systemId, importData,sourceData);
        } else {
            return modifyEvaluationRequire(entity, importData, cover);
        }
    }

    private Result<String> createEvaluationRequire(String systemId, EvaluationRequireSDTO importData, List<EvaluationRequireDO> sourceData) {
        EvaluationRequireDO entity = EvaluationRequireDO.builder()
                .systemId(systemId)
                .layerTargetId(importData.getLayerTargetId())
                .project(importData.getProject())
                .require(importData.getRequire())
                .finishState(importData.getFinishState())
                .build();
        entity.setCreateTime(LocalDateTime.now());
        return Optional.of(entity)
                .map(this.evaluationRequireRepository::save)
                .map(er->{
                    sourceData.add(er);
                    return Result.success(er.getId());
                })
                .orElse(Result.failed(String.format("导入%s测评配合需求信息，创建失败", importData.getProject())));
    }

    private Result<String> modifyEvaluationRequire(EvaluationRequireDO sourceData, EvaluationRequireSDTO importData, Boolean cover) {
        sourceData.setRequire(CheckFieldUtils.applyContent(sourceData.getRequire(), importData.getRequire(), cover));
        sourceData.setFinishState(CheckFieldUtils.applyContent(sourceData.getFinishState(), importData.getFinishState(), cover));
        sourceData.setModifyTime(LocalDateTime.now());
        return Optional.of(sourceData)
                .map(this.evaluationRequireRepository::save)
                .map(EvaluationRequireDO::getId)
                .map(Result::success)
                .orElse(Result.failed(String.format("导入%s测评配合需求信息，修改失败", importData.getProject())));
    }
}
